package com.ciei.dpagm.util;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

public class VoiceAnnouncementsUtil {
    public static String talkString(String talk,String baseFilePath) {
        ActiveXComponent sap =new ActiveXComponent("Sapi.SpVoice");
        String fileName =  System.currentTimeMillis()+".wav";;
        try{
            // 获取执行对象
            Dispatch sapo = sap.getObject();
            // 下构建文件流把生成语音文件
            sap = new ActiveXComponent("Sapi.SpFileStream");
            Dispatch spFileStream = sap.getObject();
            sap = new ActiveXComponent("Sapi.SpAudioFormat");
            Dispatch spAudioFormat = sap.getObject();
            // 设置音频流格式
            Dispatch.put(spAudioFormat, "Type", new Variant(22));
            // 设置文件输出流格式
            Dispatch.putRef(spFileStream, "Format", spAudioFormat);
            // 调用输出 文件流打开方法，创建一个.wav文件

            Dispatch.call(spFileStream, "Open", new Variant(baseFilePath+fileName), new Variant(3), new Variant(true));
            // 设置声音对象的音频输出流为输出文件对象
            Dispatch.putRef(sapo, "AudioOutputStream", spFileStream);
            // 设置音量 0到100
            Dispatch.put(sapo, "Volume", new Variant(100));
            // 设置朗读速度
            Dispatch.put(sapo, "Rate", new Variant(-2));
            // 开始朗读
            Dispatch.call(sapo, "Speak", new Variant(talk));

            // 关闭输出文件
            Dispatch.call(spFileStream, "Close");
            Dispatch.putRef(sapo, "AudioOutputStream", null);
            spAudioFormat.safeRelease();
            spFileStream.safeRelease();
            sapo.safeRelease();
            sap.safeRelease();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileName;
    }
}